package com.fgs.common.utils;

import android.os.CountDownTimer;
import android.view.View;
import android.widget.TextView;

import com.fgs.common.R;

import java.lang.ref.WeakReference;

/**
 * @author fgs
 * @date 2021/3/22
 * @description
 **/
public class SkipCountDownTimer extends CountDownTimer {

    private final WeakReference<TextView> mTextView;

    public SkipCountDownTimer(TextView textView, long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        mTextView = new WeakReference(textView);
        if (mTextView != null && mTextView.get() != null) {
            mTextView.get().setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //用弱引用 先判空 避免崩溃
        if (mTextView.get() == null) {
            timeCancel();
            return;
        }
        mTextView.get().setText(String.format(CommonUtil.getContext().getResources().getString(R.string.skip), (int) (millisUntilFinished / 1000)));
    }

    @Override
    public void onFinish() {
        //用软引用 先判空 避免崩溃
        if (mTextView.get() == null) {
            timeCancel();
            return;
        }
        mTextView.get().setText(String.format(CommonUtil.getContext().getResources().getString(R.string.skip), 0));
        mTextView.get().performClick();
    }

    public void timeCancel() {
        if (this != null) {
            this.cancel();
        }
    }

}
